import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
from tensorflow import _keras

plt.rcParams['figure.dpi'] = 180
plt.rcParams['axes.grid'] = False

fashion_mnist = tf.keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()

class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']


train_images_norm = train_images / 255.0      #像素的值除以255。
test_images_norm = test_images / 255.0

conv_model = tf.keras.Sequential([
    tf.keras.layers.Conv2D(input_shape=(28, 28, 1), filters=32, kernel_size=3, strides=1),
    tf.keras.layers.MaxPool2D(pool_size=2, strides=2),
    tf.keras.layers.Conv2D(filters=64, kernel_size=3, strides=1),
    tf.keras.layers.MaxPool2D(pool_size=2, strides=2),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(256, activation=tf.nn.relu),
    tf.keras.layers.Dense(10, activation=tf.nn.softmax) 
])

conv_model.compile(optimizer=tf.optimizers.Adam(),
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
conv_model.summary()

train_images_reshape = train_images_norm.reshape([-1, 28, 28, 1])
test_images_reshape = test_images_norm.reshape([-1, 28, 28, 1])

conv_model.fit(train_images_reshape, train_labels, epochs=5, validation_split=0.2) #训练5个回合
test_loss, test_acc = conv_model.evaluate(test_images_reshape,  test_labels, verbose=2) #model.evaluate函数预测给定输入的输出，
                                                                           #verbose=2 为每个epoch输出一行记录

print("test_loss:", test_loss,  "    测试准确率为:", test_acc)

predictions = conv_model.predict(test_images)
predictions[0]
np.argmax(predictions[0])#返回一个numpy数组中最大值的索引值。当一组中同时出现几个最大值时，返回第一个最大值的索引值


# plt.figure()
# plt.imshow(train_images[0])
# plt.colorbar()
# plt.grid(False)